<?php

namespace Modules\Admin\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class RoleController extends Controller
{
    /**
     * 显示角色列表页面
     */
    public function index(): View
    {
        return view('admin::auth.roles.index');
    }
    
    /**
     * 获取角色列表数据（用于Layui表格）
     */
    public function list(Request $request)
    {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 10);
        $offset = ($page - 1) * $limit;
        
        $query = DB::table('admin_roles')
            ->whereNull('deleted_at');
            
        // 搜索条件
        if ($request->filled('name')) {
            $query->where('name', 'like', '%' . $request->input('name') . '%');
        }
        
        // 总数
        $count = $query->count();
        
        // 获取分页数据
        $list = $query->orderBy('id', 'desc')
            ->offset($offset)
            ->limit($limit)
            ->get();
            
        return response()->json([
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $list
        ]);
    }
    
    /**
     * 显示创建角色页面
     */
    public function create(): View
    {
        // 获取所有权限
        $permissions = DB::table('admin_permissions')
            ->whereNull('deleted_at')
            ->orderBy('id')
            ->get();
            
        return view('admin::auth.roles.create', compact('permissions'));
    }
    
    /**
     * 保存新角色
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|max:50|unique:admin_roles,name',
            'description' => 'nullable',
            'permissions' => 'nullable|array'
        ]);
        
        // 开始事务
        DB::beginTransaction();
        
        try {
            // 创建角色
            $roleId = DB::table('admin_roles')->insertGetId([
                'name' => $request->input('name'),
                'description' => $request->input('description'),
                'status' => 1,
                'created_at' => now(),
                'updated_at' => now()
            ]);
            
            // 关联权限
            $permissions = $request->input('permissions', []);
            $rolePermissions = [];
            
            foreach ($permissions as $permissionId) {
                $rolePermissions[] = [
                    'role_id' => $roleId,
                    'permission_id' => $permissionId,
                    'created_at' => now(),
                    'updated_at' => now()
                ];
            }
            
            if (!empty($rolePermissions)) {
                DB::table('admin_role_permissions')->insert($rolePermissions);
            }
            
            DB::commit();
            
            return response()->json([
                'code' => 0,
                'msg' => '添加成功'
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            
            return response()->json([
                'code' => 1,
                'msg' => '添加失败：' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 显示编辑角色页面
     */
    public function edit($id): View
    {
        $role = DB::table('admin_roles')->where('id', $id)->first();
        
        if (!$role) {
            abort(404, '角色不存在');
        }
        
        // 获取所有权限
        $permissions = DB::table('admin_permissions')
            ->whereNull('deleted_at')
            ->orderBy('id')
            ->get();
            
        // 获取角色已有权限
        $rolePermissions = DB::table('admin_role_permissions')
            ->where('role_id', $id)
            ->pluck('permission_id')
            ->toArray();
            
        return view('admin::auth.roles.edit', compact('role', 'permissions', 'rolePermissions'));
    }
    
    /**
     * 更新角色
     */
    public function update(Request $request, $id)
    {
        $role = DB::table('admin_roles')->where('id', $id)->first();
        
        if (!$role) {
            return response()->json([
                'code' => 1,
                'msg' => '角色不存在'
            ]);
        }
        
        $request->validate([
            'name' => 'required|max:50|unique:admin_roles,name,' . $id,
            'description' => 'nullable',
            'permissions' => 'nullable|array'
        ]);
        
        // 开始事务
        DB::beginTransaction();
        
        try {
            // 更新角色
            DB::table('admin_roles')->where('id', $id)->update([
                'name' => $request->input('name'),
                'description' => $request->input('description'),
                'updated_at' => now()
            ]);
            
            // 删除旧权限关联
            DB::table('admin_role_permissions')->where('role_id', $id)->delete();
            
            // 关联新权限
            $permissions = $request->input('permissions', []);
            $rolePermissions = [];
            
            foreach ($permissions as $permissionId) {
                $rolePermissions[] = [
                    'role_id' => $id,
                    'permission_id' => $permissionId,
                    'created_at' => now(),
                    'updated_at' => now()
                ];
            }
            
            if (!empty($rolePermissions)) {
                DB::table('admin_role_permissions')->insert($rolePermissions);
            }
            
            DB::commit();
            
            return response()->json([
                'code' => 0,
                'msg' => '更新成功'
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            
            return response()->json([
                'code' => 1,
                'msg' => '更新失败：' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 删除角色
     */
    public function destroy($id)
    {
        $role = DB::table('admin_roles')->where('id', $id)->first();
        
        if (!$role) {
            return response()->json([
                'code' => 1,
                'msg' => '角色不存在'
            ]);
        }
        
        // 开始事务
        DB::beginTransaction();
        
        try {
            // 删除角色权限关联
            DB::table('admin_role_permissions')->where('role_id', $id)->delete();
            
            // 删除角色用户关联
            DB::table('admin_role_users')->where('role_id', $id)->delete();
            
            // 软删除角色
            DB::table('admin_roles')
                ->where('id', $id)
                ->update(['deleted_at' => now()]);
                
            DB::commit();
            
            return response()->json([
                'code' => 0,
                'msg' => '删除成功'
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            
            return response()->json([
                'code' => 1,
                'msg' => '删除失败：' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 更新角色状态
     */
    public function updateStatus(Request $request, $id)
    {
        $role = DB::table('admin_roles')->where('id', $id)->first();
        
        if (!$role) {
            return response()->json([
                'code' => 1,
                'msg' => '角色不存在'
            ]);
        }
        
        $status = $request->input('status');
        
        if (!in_array($status, [0, 1])) {
            return response()->json([
                'code' => 1,
                'msg' => '状态值无效'
            ]);
        }
        
        DB::table('admin_roles')->where('id', $id)->update([
            'status' => $status,
            'updated_at' => now()
        ]);
        
        return response()->json([
            'code' => 0,
            'msg' => '状态更新成功'
        ]);
    }
} 